from itsdangerous.jws import TimedJSONWebSignatureSerializer as TJWSSerializer
from django.conf import settings

from users.models import User


def generate_verify_url(user):
    token = {
        'user_id': user.id,
        'email': user.email
    }
    # 将token进行加密处理
    serializer = TJWSSerializer(settings.SECRET_KEY, expires_in=300)
    token = serializer.dumps(token)
    # 拼接验证网址，携带参数token
    verify_url = '%s?token=%s' % (settings.EMAIL_VERIFY_URL, token.decode())

    return verify_url


def decode_token(token):
    serializer = TJWSSerializer(settings.SECRET_KEY, expires_in=300)
    try:
        token = serializer.loads(token)
        user_id = token.get('user_id')
        user = User.objects.get(id=user_id)
    except Exception:
        return None
    return user
